////
//
/// \file ./src/local_decl_node.cpp
//
//  Copyright 2007, 2008 Chandler Carruth
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations
//  under the License.
//
////

#include <inc/parser/local_decl_node.hpp>

#include <string>

#include <boost/scoped_ptr.hpp>

#include <inc/parser/ws_parser.hpp>
#include <inc/parser/parse_tree_node.hpp>
#include <inc/parser/variable_decl_node.hpp>

namespace inc {
namespace parser {

using std::string;
using boost::scoped_ptr;

/// \brief Basic constructor for a local variable declaration
/// \author Chandler Carruth
/// \date 2008.10.04

LocalDeclNode::LocalDeclNode()
    : ws(new WSParser)
{}

/// \brief Empty destructor, all members are smart pointers
/// \author Chandler Carruth
/// \date 2008.10.04

LocalDeclNode::~LocalDeclNode()
{}

/// \brief Parse a local variable declaration in INC
/// \author Chandler Carruth
/// \date 2008.10.04
///
/// Parse out a local variable declaration. These are standard variable
/// declarations but prefixed with the keyword "local".

bool
LocalDeclNode::parse( const iterator &first,
                      const iterator &last,
                      iterator &last_parsed )
{
  assert( get_text().empty() && !variable_decl
          && "This node was parsed more than once!" );

  if( std::distance( first, last ) >= 5
      && string( first, first + 5 ) == "local" )
  {
    iterator current = first + 5;
    if( ws->parse_ws( current, last, last_parsed ) )
    {
      current = last_parsed;

      scoped_ptr<VariableDeclNode> tmp_decl( new VariableDeclNode );
      if( tmp_decl->parse( current, last, last_parsed ) )
      {
        current = last_parsed;
        if( ws->parse_eol_ws( current, last, last_parsed ) )
        {
          set_text( string( first, last_parsed ) );
          variable_decl.swap( tmp_decl );
          return true;
        }
      }
    }
  }

  //  No valid parse found.
  last_parsed = first;
  return false;
}

/// \brief Convenience getter for the variable declaration node
/// \author Chandler Carruth
/// \date 2008.10.04

VariableDeclNode*
LocalDeclNode::get_variable_decl() const
{
  return variable_decl.get();
}

} //  end parser namespace
} //  end inc namespace
